#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import g
import re
import time
import datetime
import gzip
import urllib
import os
import sys
from urllib.parse import urlparse, parse_qs
from subprocess import Popen, PIPE, STDOUT, DEVNULL
from telebot import types

saveNowTime = None #чтобы не было пропуска кликов, не убегала каждая секция по временне было пропуска кликов, не убегала каждая секция по времении

#------------------------------------------------------------------------------
def checkIsRunning(config):
    try:

        pidF = os.path.isfile(config['service']['pidFile'])
        lockF = os.path.isfile(config['service']['lockFile'])

        if pidF:
            if lockF:
                raise RuntimeError('try run application twice.... exiting')
            else:
                raise RuntimeError('app is still running without lock file.... exiting')
                #readPid = int(.readline().strip())
                #kill #TODO

        if lockF:
            print('app finished with failure last time...removing', config['service']['lockFile'])
            os.remove(config['service']['lockFile'])

        with open(config['service']['pidFile'], 'w') as f:
            f.write(str(os.getpid()))
            f.close()

        with open(config['service']['lockFile'], 'w') as f:
            f.write('lock')
            f.close()

        print('starting OK')

    except RuntimeError as err:

        print(err)
        print(
              'pid:'+config['service']['pidFile']
            , 'lock:' + config['service']['lockFile']
        )
        sys.exit(-1)

    except BaseException as err:

        print(g.errStr(err, 'checkIsRunning'))
        print(
              'pid:'+config['service']['pidFile']
            , 'lock:' + config['service']['lockFile']
        )
        sys.exit(-1)

    #sys.exit(0) # DELETEME

#------------------------------------------------------------------------------
def removeLockAndPidFiles(config):
    try:
        os.remove(config['service']['lockFile'])
        os.remove(config['service']['pidFile'])
    except BaseException as err:
        print(g.errStr(err, 'removeLockAndPidFiles'))
        g.printErrEx(err, 'removeLockAndPidFiles')

#------------------------------------------------------------------------------
## @brief get percent current value of value100
#
#  @param[in] valcurrent - current value
#  @param[in] val100 - 100 % value
def getPersent(valcurrent, val100):
    try:
        if None == val100 or 0 == val100 or None == valcurrent:
            return 0
        v100 = float(val100);
        vcur = float(valcurrent);
        return int(float((100.0 * vcur) / v100))
    except BaseException as err:
        g.printErrEx(
              err
            , 'getPersent'
        )
        return 0

#------------------------------------------------------------------------------
def gzipFile(file):
    with open(file, 'rb') as fr:
        content = fr.read()
        f = gzip.open(file+ '.gz', 'wb')
        f.write(content)
        f.close()
        return file + '.gz'

#------------------------------------------------------------------------------
class cbKey:

    def __init__(self, id=-1, text="", data=""):
        self.id=id
        self.text=text
        self.data=data

    def AsCbStr(self):
        return f"{str(self.id)}.{str(self.data)}"

    def fromCBkey(self, keyAsCbStr):
        s=keyAsCbStr.split('.')
        self.id=s[0]
        self.data=s[1]
        return self

#------------------------------------------------------------------------------
class ExtraEnum:

    def __init__(self):
        self.keys={}

    def add(self, id, text, data=''):
        self.keys[str(id)] = cbKey(str(id), text, data)

    def k(self, id):
        return self.keys[str(id)]

#------------------------------------------------------------------------------
class InlineMyMarkup():

    def __init__(self):
        self._markup = types.InlineKeyboardMarkup()

    def add(self, cb):
        self._markup.add(types.InlineKeyboardButton(cb.text, callback_data=cb.AsCbStr()), row_width=1)

    def addNoCb(self, txt, url):
        self._markup.add(types.InlineKeyboardButton(txt, url=url), row_width=1)

    def get(self):
        return self._markup

#------------------------------------------------------------------------------
tformat='%Y-%m-%d %H:%M:%S'

def toHumanReadable(ts):
    return ts.strftime(tformat)

def timeNowGMT():
    return datetime.datetime.now().strftime(tformat)

def timeNowPlusDelta(days=0, hours=0):
    return toHumanReadable(datetime.datetime.now() + datetime.timedelta(days=days, hours=hours))

#------------------------------------------------------------------------------
# useful functions
def isTextEqual(text, cb):
    return cb.message.text == text

def isMarkupEqual(markup, cb):
    return cb.message.reply_markup == markup

def allEqual(text, markup, cb):
    return isTextEqual(text,cb) and isMarkupEqual(markup, cb)

async def editMessage(bot, cb, text, markup=None):
    markupNew = cb.message.reply_markup if not markup else markup

    if allEqual(text, markupNew, cb):
        return 

    if isTextEqual(text,cb):
        await bot.edit_message_reply_markup(cb.message.chat.id, cb.message.message_id, reply_markup=markupNew)
    else:
        await bot.edit_message_text(text, cb.message.chat.id, cb.message.message_id, reply_markup=markupNew)

